import type { CascaderTypeListResult } from "@/api/types";
import type { UseBaseTable } from "@/composables";
import { reactive } from "vue";
import { cascaderTypeApi } from "@/api";
import { useBaseTable } from "@/composables";
import { apiCall } from "@/utils/http/apiCall";

/**
 * 字典查询表单
 */
export interface Query {
    /** 字典名称 */
    name: string | null;
    /** 字典编码 */
    code: string | null;
}

interface UseCascaderTypeTable extends UseBaseTable<CascaderTypeListResult> {
    /** 查询表单 */
    tableQuery: Query;
    /** 获取数据 */
    fetchTableData: () => void;
    /** 查询 */
    handleTableQuery: () => void;
    /** 重置查询 */
    resetTableQuery: () => void;
}

/** 字典列表逻辑封装 */
export function useCascaderTypeTable(): UseCascaderTypeTable {
    const { tableLoading, tableData, tablePage } = useBaseTable<CascaderTypeListResult>();

    /** 查询表单 */
    const tableQuery = reactive<Query>({
        name: null,
        code: null,
    });

    /** 获取字典列表 */
    function fetchTableData(): void {
        tableLoading.value = true;

        const payload = {
            pageNum: tablePage.value.pageNum,
            pageSize: tablePage.value.pageSize,
            name: tableQuery.name || null,
            code: tableQuery.code || null,
        };

        apiCall(
            () => cascaderTypeApi.page(payload),
            (data, resp) => {
                tableData.value = data || [];
                if ("page" in resp) {
                    tablePage.value.total = resp.page.total;
                }
            },
            {
                onFinally: () => {
                    tableLoading.value = false;
                },
            },
        );
    }

    /** 查询 */
    function handleTableQuery(): void {
        tablePage.value.pageNum = 1;
        fetchTableData();
    }

    /** 重置查询 */
    function resetTableQuery(): void {
        tableQuery.name = "";
        tableQuery.code = "";
        handleTableQuery();
    }

    return {
        tableLoading,
        tableData,
        tablePage,
        tableQuery,
        fetchTableData,
        handleTableQuery,
        resetTableQuery,
    };
}
